package net.hvacapp.cmvrfforandroid.ui;

import android.annotation.TargetApi;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

import net.hvacapp.cmvrfforandroid.AppManager;
import net.hvacapp.cmvrfforandroid.HvacappApplication;
import net.hvacapp.cmvrfforandroid.R;
import net.hvacapp.cmvrfforandroid.utils.SystemStatusManager;
import net.hvacapp.cmvrfforandroid.utils.WindowUtils;
import net.hvacapp.cmvrfforandroid.widget.CubeadToast;

/**
 * BaseActivity
 *
 * @author <a href="http://www.trinea.cn" target="_blank">Trinea</a> 2013-6-1
 */
public abstract class BaseActivity extends AppCompatActivity {

    protected Context context;
    protected HvacappApplication mApp;

//    protected Toolbar mToolbar = null;
//
//    private int mMenuItemIds[];
//    private int mMenuItemIcons[];
//    private int mMenuItemModes[];
//    private String mMenuItemTitles[];

    protected TextView mTitle;
    protected TextView mBack;
    protected TextView mBtn1;
    protected TextView mBtn2;

    /**
     * menuItem固定在Toolbar上显示
     */
    protected final int ALWAYS = MenuItem.SHOW_AS_ACTION_ALWAYS;
    /**
     * 如果有足够的空间，menuItem在Toolbar上显示，否则显示在溢出菜单中
     */
    protected final int IF_ROOM = MenuItem.SHOW_AS_ACTION_IF_ROOM;
    /**
     * menuItem显示在溢出菜单中
     */
    protected final int NEVER = MenuItem.SHOW_AS_ACTION_NEVER;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setStatusBar();

        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        AppManager.getAppManager().addActivity(this);

        context = getApplicationContext();
        mApp = (HvacappApplication) getApplication();
    }

    /**
     * activity view加载完后调用此方法， 每个继承BaseActivity的必须继承此方法 并添加@AfterViews注解
     */
    protected void viewDidLoad() {
        mTitle = (TextView)findViewById(R.id.tv_navigation_title);
        mBack = (TextView)findViewById(R.id.tv_navigation_back);
        mBtn1 = (TextView)findViewById(R.id.tv_navigation_btn1);
        mBtn2 = (TextView)findViewById(R.id.tv_navigation_btn2);

        initBoot();
        initData(getIntent());

    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onStop() {
//        if (!WindowUtils.isAppOnForeground(this)) {
//            // 程序进入后台
//            if (mApp.isForeground()) {
//                mApp.setForeground(false);
//                mApp.setFloatWMHide();
//            }
//        }
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        AppManager.getAppManager().finishActivity(this);
        super.onDestroy();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_MENU) {//MENU键
            //监控/拦截菜单键
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 初始化启动项
     */
    public abstract void initBoot();

    /**
     * 初始化数据
     */
    public abstract void initData(Intent intent);

    /**
     * 获取当前页的名称
     *
     * @return
     */
    public abstract String getName();

    /**
     * 吐司信息提示
     *
     * @param message
     */
    public void showMessage(String message) {
        CubeadToast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }

    /**
     * 获取屏幕截图
     * @return 截图的bitmap对象
     */
    public Bitmap getScreenBitmap() {
        //1.构建Bitmap
        DisplayMetrics dm = new DisplayMetrics();
        //获取屏幕信息
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        int w = dm.widthPixels;
        int h = dm.heightPixels;

        Bitmap Bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);

        //2.获取屏幕
        View decorview = this.getWindow().getDecorView();
        decorview.setDrawingCacheEnabled(true);
        Bmp = decorview.getDrawingCache();
        return Bmp;
    }

    /**
     * 短暂显示Toast提示(来自res) *
     */
    protected void showMessage(int resId) {
        Toast.makeText(this, getString(resId), Toast.LENGTH_SHORT).show();
    }

    /**
     * 长时间显示Toast提示(来自res) *
     */
    protected void showLongToast(int resId) {
        Toast.makeText(this, getString(resId), Toast.LENGTH_LONG).show();
    }

    /**
     * 长时间显示Toast提示(来自String) *
     */
    protected void showLongToast(String text) {
        Toast.makeText(this, text, Toast.LENGTH_LONG).show();
    }

    protected void startActivity(Class<?> cls) {
        startActivity(cls, null);
    }

    protected void startActivity(Class<?> cls, Bundle bundle) {
        Intent intent = new Intent(this, cls);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivity(intent);
        overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
    }

    /**
     * 带有右进右出动画的退出 *
     */
    public void finish() {
        super.finish();
        overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
    }

    /**
     * 默认退出 *
     */
    protected void defaultFinish() {
        super.finish();
    }

    /**
     * 创建进度条对话框
     *
     * @param context
     * @param tip
     * @return
     */
    protected Dialog createProgressBarDialog(Context context, String tip) {
        final Dialog dialog = new Dialog(context, R.style.dialog);
        dialog.setContentView(R.layout.progressbar_dialog);
        dialog.setCanceledOnTouchOutside(false);
        Window window = dialog.getWindow();
        WindowManager.LayoutParams lp = window.getAttributes();
        int width = WindowUtils.getScreenWidth(context);
        lp.width = (int) (0.6 * width);

        TextView titleTxtv = (TextView) dialog.findViewById(R.id.tvLoad);

        titleTxtv.setText(tip);
        return dialog;
    }

    /**
     * 设置Tollbar
     *
     * @param title          标题
     */
    protected void setupToolbar(String title) {
        mBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        mTitle.setText(title);

//        if (mToolbar == null) {
//            mToolbar = (Toolbar) findViewById(R.id.toolbar);
//        }
//        mToolbar.setTitle(title);
//        // 调用此方法会使onCreateOptionsMenu方法执行
//        setSupportActionBar(mToolbar);
    }

    protected void setButton1Info(String text, View.OnClickListener listener) {
        if (text == null) {
            mBtn1.setVisibility(View.INVISIBLE);
            return;
        }
        mBtn1.setVisibility(View.VISIBLE);
        mBtn1.setText(text);
        if (listener != null) {
            mBtn1.setOnClickListener(listener);
        }
    }

    protected void setButton2Info(String text, View.OnClickListener listener) {
        if (text == null) {
            mBtn2.setVisibility(View.INVISIBLE);
            return;
        }
        mBtn2.setVisibility(View.VISIBLE);
        mBtn2.setText(text);
        if (listener != null) {
            mBtn2.setOnClickListener(listener);
        }
    }

    protected void hidBackBtn() {
        mBack.setVisibility(View.INVISIBLE);
    }

    protected void setupToolbar(int resId, String title, View.OnClickListener listener) {
        if (resId != 0) {
            mBack.setText(resId);
        }
        if (listener == null) {
            mBack.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    finish();
                }
            });
        }
        else {
            mBack.setOnClickListener(listener);
        }
        mTitle.setText(title);

//        if (mToolbar == null) {
//            mToolbar = (Toolbar) findViewById(R.id.toolbar);
//        }
//        mToolbar.setTitle(title);
//        // 调用此方法会使onCreateOptionsMenu方法执行
//        setSupportActionBar(mToolbar);
//
//        ActionBar actionBar = getSupportActionBar();
//        //必须在调用setSupportActionBar()方法后再设置icon和点击监听，否则无效
//        if (resId == 0) {
//            actionBar.setDisplayHomeAsUpEnabled(true);
//        }
//        else {
//            actionBar.setHomeAsUpIndicator(resId);
//            actionBar.setDisplayHomeAsUpEnabled(true);
//        }
//        if (listener == null) {
//            mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    finish();
//                }
//            });
//        }
//        else {
//            mToolbar.setNavigationOnClickListener(listener);
//        }
    }

    /**
     * 设置Tollbar的menu
     *
     * @param menuItemIds    menu项id数组
     * @param menuItemIcons  menu项icon数组
     * @param menuItemTitles menu项标题数组
     * @param menuItemModes  menu项显示模式
     */
    protected void setupToolbarMenuItem(int menuItemIds[], int menuItemIcons[], String menuItemTitles[], int menuItemModes[]) {
//        this.mMenuItemIds = menuItemIds;
//        this.mMenuItemIcons = menuItemIcons;
//        this.mMenuItemTitles = menuItemTitles;
//        this.mMenuItemModes = menuItemModes;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            addMenuItemForToolbarSDK11(menu);
        } else {
            addMenuItemForToolbarSDK9(menu);
        }

        return true;
    }

    /**
     * 添加menuItem
     *
     * @param menu 菜单
     */
    @TargetApi(11)
    private void addMenuItemForToolbarSDK11(Menu menu) {
//        if (mMenuItemIcons != null || mMenuItemIds != null) {
//            MenuItem menuItem = null;
//            for (int i = 0; i < mMenuItemIcons.length; i++) {
//                menuItem = menu.add(R.id.toolbar, mMenuItemIds[i], i, mMenuItemTitles == null ? "" : mMenuItemTitles[i])
//                        .setIcon(mMenuItemIcons[i]);
//                menuItem.setShowAsAction(mMenuItemModes == null ? IF_ROOM : mMenuItemModes[i]);
//            }
//        }
    }

    /**
     * 添加menuItem
     *
     * @param menu 菜单
     */
    @TargetApi(9)
    private void addMenuItemForToolbarSDK9(Menu menu) {
//        if (mMenuItemIcons != null || mMenuItemIds != null) {
//            MenuItem menuItem = null;
//            for (int i = 0; i < mMenuItemIcons.length; i++) {
//                menuItem = menu.add(R.id.toolbar, mMenuItemIds[i], i, mMenuItemTitles == null ? "" : mMenuItemTitles[i])
//                        .setIcon(mMenuItemIcons[i]);
//                MenuItemCompat.setShowAsAction(menuItem, mMenuItemModes == null ? IF_ROOM : mMenuItemModes[i]);
//            }
//        }
    }

    /**
     * 设置状态栏颜色，使状态栏与应用颜色一体化(4.4以及4.4以上版本可以使用)
     */
    private void setStatusBar()
    {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
        {
            Window win = getWindow();
            WindowManager.LayoutParams winParams = win.getAttributes();
            final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
            winParams.flags |= bits;
            win.setAttributes(winParams);
        }
        SystemStatusManager tintManager = new SystemStatusManager(this);
        tintManager.setStatusBarTintEnabled(true);
        tintManager.setStatusBarTintColor(getResources().getColor(R.color.toolbar_bg));
    }

}
